package com.kehutong.message.admin;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import com.kehutong.common.util.Token;
import com.kehutong.message.service.MiniMessageService;
import org.coraframework.authz.HasPermission;
import org.coraframework.bean.valid.ValidResult;
import org.coraframework.inject.Inject;
import org.coraframework.json.JSONObject;
import org.coraframework.logger.Logger;
import org.coraframework.logger.LoggerFactory;
import org.coraframework.mvc.MvcAction;
import org.coraframework.mvc.http.Bean;
import org.coraframework.mvc.http.ReqMapping;
import org.coraframework.mvc.http.result.Result;
import org.coraframework.orm.Pool;
import org.coraframework.orm.jdbc.JdbcSession;
import org.coraframework.orm.jdbc.Page;
import org.coraframework.util.Objects;
import com.kehutong.common.enums.TemplateType;
import com.kehutong.message.entity.TemplateSetting;
import com.kehutong.message.service.TemplateSettingService;
import com.kehutong.message.urlConfig.WebChatUrlConfig;
import com.kehutong.webchat.service.WeChatService;

/**
 * 公众号、短消息模板设置
 * 
 * @author liuzhen (liuxing521a@163.com)
 * @createTime 2020年5月21日 上午9:52:37
 */
@MvcAction
@ReqMapping("/admin/setting/template")
public class TemplateSettingController {

    protected Logger logger = LoggerFactory.getLogger(TemplateSettingController.class);
	
	@Inject
	private JdbcSession jdbcSession;
	@Inject
    private WeChatService weChatService;
	@Inject
    private WebChatUrlConfig webChatUrlConfig;
	@Inject
    private TemplateSettingService templateSettingService;
	@Inject
    private MiniMessageService miniMessageService;

	@ReqMapping("/typeEnums")
    public Object typeEnums(){
	    return Result.success(Arrays.asList(TemplateType.values()));
    }
	
    @HasPermission("setting:template:view")
    @ReqMapping("/list")
    public Object list(JSONObject jsonObject) {
    	final Page<TemplateSetting> page = jdbcSession.findPage(TemplateSetting.class)
                                                      .eq("deleted", false)
                                                      .order("createTime", "desc")
                                                      .page(jsonObject)
                                                      .exe();
    	
    	return Result.success(page);
    }

    @ReqMapping("/listWebchat")
    public Object listWebchat(String appId) throws Exception {
        String access_token = weChatService.getAccessToken(appId);
        JSONObject result = webChatUrlConfig.post("/cgi-bin/template/get_all_private_template", http -> {
            http.addParam("access_token", access_token);
        });
        Page<JSONObject> page = new Page<>();
        List<JSONObject> resultJson = new ArrayList<>();
        if (Objects.isNull(result)){
            return Result.success(page);
        }
        if (Objects.isEmpty(result.getJSONArray("template_list"))){
            logger.info("appId:{},access_token:{},result:{}", appId, access_token, result);
            return Result.success(page);
        }
        result.getJSONArray("template_list").forEach(e -> {
            JSONObject j = (JSONObject) e;
            if (Objects.isEmpty(j.getString("example")) || Objects.isEmpty(j.getString("primary_industry")))
                return;

            resultJson.add(j);
        });
        page.setList(resultJson);
	    return Result.success(page);
    }

    @HasPermission("setting:template:view")
    @ReqMapping("/get")
    public Object get(String id) {
    	TemplateSetting item = Pool.get(TemplateSetting.class, id);
    	return Result.success(item);
    }
    
    @Bean(newInstance=true, copy=true)
    @HasPermission("setting:template:edit")
    @ReqMapping("/save")
    public Object save(TemplateSetting setting, ValidResult result) {
    	if (result.hasError()) {
    		return Result.error(0, result.getErrorMessage());
    	}

        if (checkDuplicateByType(setting.getId(), setting.getTemplateType())) {
            return Result.error(0, "模板类型已存在");
        }

        templateSettingService.syncGlobalConfig(setting.getBusinessType(), setting.getTemplateType(), setting.getId());
    	
    	jdbcSession.insert(setting);
    	return Result.success();
    }

  
    @Bean(newInstance=false, copy=true)
    @HasPermission("setting:template:edit")
    @ReqMapping("/update")
    public Object update(TemplateSetting setting, ValidResult result) {
    	if (result.hasError()) {
    		return Result.error(0, result.getErrorMessage());
    	}

    	if (checkDuplicateByType(setting.getId(), setting.getTemplateType())) {
    	    return Result.error(0, "模板类型已存在");
        }

        templateSettingService.syncGlobalConfig(setting.getBusinessType(), setting.getTemplateType(), setting.getId());

    	jdbcSession.updateById(setting);
    	return Result.success();
    }

    private boolean checkDuplicateByType(String id, TemplateType templateType){
        TemplateSetting template = jdbcSession.findOne(TemplateSetting.class)
                                              .eq("templateType", templateType)
                                              .eq("deleted", false)
                                              .exe();
        return Objects.nonNull(template) && !id.equals(template.getId());
    }

    @HasPermission("setting:template:edit")
    @ReqMapping("/delete")
    public Object delete(String id) {
    	TemplateSetting setting = Pool.get(TemplateSetting.class, id);

    	if (Objects.nonNull(setting)) {
    		setting.setDeleted(true);
    		jdbcSession.updateById(setting);
    	}
    	
    	return Result.success();
    }

}
